<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * BackendPro
 *
 * A website backend system for developers for PHP 4.3.2 or newer
 *
 * @package         conlabz CMS
 * @author          Christian Schneider
 * @copyright       Copyright (c) 2009
 * @license        
 * @link            http://www.conlabz.de
 * @filesource
 */

// ---------------------------------------------------------------------------

/**
 * Menu
 *
 * Allows to manage menu informations
 *
 * @package         conlabz CMS
 * @subpackage      Controllers
 */
class Menu extends User_Controller {
	
	function Menu( ) {
		parent::User_Controller( );
		
		$this->load->helper( 'form' );

		// Check for access permission
		// needs to be defined as a resource over the admin area
		check( 'Menu' );

		// Load the validation library
		$this->load->library( 'validation' );

		// Load the domain and website model
		$this->load->model( 'menu_model' );
		$this->load->model( 'website_model' );
		
		// Load the article model
		$this->lang->module_load( 'article', 'menu' );

		// Set breadcrumb
		$this->bep_site->set_crumb( $this->lang->line( 'menu' ), 'article/user/menu' );
				
		log_message( 'debug', 'conlabz CMS : Menu class loaded' );
	}	
	
	/**
	 * View Menu Position
	 *
	 * @access public
	 */
	function index( ) {
		// Get Menu Position Infomation
		$data['menu_position'] = array( );
		$data['menu_position'] = $this->menu_model->getMenuPosition( );
		
		// Display Page
		$data['header'] = $this->lang->line( 'menu_position_overview' );
		$data['page'] = $this->config->item('backendpro_template_user') . "/view_menu_position";
		$data['menu'] = $this->website_model->getWebsiteUserMenu( );
		$data['module'] = 'article';
		$this->load->view( $this->_container, $data );
	}
	
	/**
	 * View Menu for a single position
	 *
	 * @access public
	 */
	function overview( $position ) {
		// Include menu Javascript code
		//$this->bep_site->set_asset('shared','js','interface.js');
		//$this->bep_site->set_asset('shared','js','inestedsortable.js');
		
		// Get Menu Infomation
		$data['menu_content'] = array( );
		$menu = $this->menu_model->getMenuList( $position );
		//don't display first entry
		$menu[0]['title'] = 'Standard';
		$data['menu_content'] = '<ul id="list-container">';
		$data['menu_content'] .= $this->_array_to_ul( $menu, $position );
		$data['menu_content'] .= "</ul>\n";
		// Display Page
		$data['position'] = $position;
		$data['header'] = $this->lang->line( 'menu_overview' );
		$data['page'] = $this->config->item('backendpro_template_user') . "/view_menu";
		$data['menu'] = $this->website_model->getWebsiteUserMenu( );
		$data['module'] = 'article';
		$this->load->view( $this->_container, $data );
	}

	/**
	 * View types of possible Menu
	 *
	 * @access public
	 */
	function type( $position ) {
		//@todo: load information dynamically by feature set for the type of website
		$data['features'] = $this->website_model->getComponentByFeature( );
		// Display Page
		$data['position'] = $position;
		$data['header'] = $this->lang->line( 'menu_select_type' );
		$data['page'] = $this->config->item('backendpro_template_user') . "/view_menu_type";
		$data['menu'] = $this->website_model->getWebsiteUserMenu( );
		$data['module'] = 'article';
		$this->load->view( $this->_container, $data );
	}
	
	function _array_to_ul( $var, $position = 0 ){
		$menu_list = '';
		foreach( $var as $key => $value ) {
			if( array_key_exists( 'title', $value ) ){
				//get the three elements to calculate the parent element
				if( array_key_exists( 'type', $value ) ){
					$type = $value['type'];
					unset( $value['type'] );
				}
				if( array_key_exists( 'type_id', $value ) ){
					$type_id = $value['type_id'];
					unset( $value['type_id'] );
				}
				if( array_key_exists( 'depth', $value ) ){
					$depth = $value['depth'];
					unset( $value['depth'] );
				}
				if( array_key_exists( 'id', $value ) ){
					$menu_id = $value['id'];
					unset( $value['id'] );
				}					
				//get title
				if( !empty( $type ) ){
					$menu_list .= '<li class="sortable-element-class menu-li" id="ele-'.$key.'"><div class="menu-title">';
					$menu_list .= $value['title'];
					unset( $value['title'] );
					$menu_list .= '</div><div class="menu-active">';
					//@todo:
					$value['active'] = "true";
					$menu_list .= $value['active'] ? $this->bep_assets->icon( 'tick' ) : $this->bep_assets->icon( 'cross' );
					unset( $value['active'] );
					$menu_list .= '</div><div class="menu-up">';
					$menu_list .= '<a href="'. site_url('article/user/menu/up/'.$value['url'] . '/'.$position) .'">';
					$menu_list .= $this->bep_assets->icon( 'arrow_up' );
					$menu_list .= '</a></div><div class="menu-down">';
					$menu_list .= '<a href="'. site_url('article/user/menu/down/'.$value['url'] . '/'.$position ) .'">';
					$menu_list .= $this->bep_assets->icon( 'arrow_down' );
					$menu_list .= '</a></div><div class="menu-pencil">';
					$menu_list .= '<a href="'. site_url('article/user/menu/form/'.$type.'/'.$type_id ) .'">';
					$menu_list .= $this->bep_assets->icon( 'pencil' );
					$menu_list .= '</a></div><div class="menu-translate">';
					//@todo: language should come from database
					$menu_list .= '<a href="'. site_url('article/user/menu/translate/'.$menu_id.'/'.$position.'/2' ) .'">';
					$menu_list .= $this->bep_assets->icon( 'flag-gb' );
					$menu_list .= '</a></div>';
            		$menu_list .= '<div class="menu-delete">'. form_checkbox( 'select[]', $value['url'], FALSE ). '</div><div class="submenu"><ul>';
					unset( $value['url'] );
				}
				$menu_list .= $this->_array_to_ul( $value, $position );
				if( !empty( $type ) ){
					$menu_list .= "</ul></div>\n";
					$menu_list .= "</li>\n";
				}
			} else {
				if( !empty( $value ) ){
					$menu_list .= '<li class="sortable-element-class" id="ele-'.$key.'"><div class="menu-title">'. $value['title'] . '</div><div class="menu-edit">Edit</div><div class="menu-delete">'. form_checkbox( 'select[]', $value['url'], FALSE ). "</div></li>\n";
				} //if
	        }
		} //foreach
		return $menu_list;
    }
	
	/**
	 * Get Menu Details
	 *
	 * Load menu detail values from the submitted form
	 *
	 * @access private
	 * @return array
	 */
	function _get_menu_details(){
		$data['type_id'] = $this->input->post( 'type_id' );
		$data['menu_id'] = $this->input->post( 'menu_id' );
		$data['active'] = $this->input->post( 'active' );
		$data['menu_position_id'] = $this->input->post( 'menu_position_id' );
		$data['url'] = $this->input->post( 'url' );
		$data['title'] = $this->input->post( 'title' );
		$data['type'] = $this->input->post( 'type' );
		//@todo: ???
		if( $data['type'] == 'events' ){
			$temp = 'start=' .$this->input->post( 'menu_start' ).
					';end=' . $this->input->post( 'menu_end' ).
					';highlights=' . $this->input->post( 'menu_highlights' );
			$data['type_id'] = $temp;
		}
		
		return $data;
	}
	
	/**
	 * Set Menu Defaults
	 *
	 * Specify what values should be shown in the fields when creating
	 * a new menu by default
	 *
	 * @access private
	 * @todo specify the fields
	 */
	function _set_menu_defaults( ){
		//$this->validation->set_default_value('field1','value');
		//$this->validation->set_default_value('field2','value');
	}
	
	/**
	 * Display Menu Form
	 *
	 * @access public
	 * @param integer $id Article ID
	 */
	function form( $id = NULL ) {
		// VALIDATION FIELDS
		$fields['id'] = "ID";
		$fields['menu_position_id'] = $this->lang->line( 'menu_position_id' );
		$fields['type_id'] = $this->lang->line('type_id');
		$fields['menu_id'] = $this->lang->line('menu_id');
		$fields['active'] = $this->lang->line('active');
		$this->validation->set_fields( $fields );

		$position = $this->input->post( 'position' );
		$type = $this->input->post( 'type' );
		
		// Setup validation rules
		if( is_null( $id ) ) {
			// Use create article rules (make sure no-one has the same short name)
			//@todo: what's about the events??? |required
			$rules['type_id'] = "trim|required";
		} else {
			// Use edit article rules (make sure no-one other than the current user has the same short name)
			//@todo: see above |required
			$rules['type_id'] = "trim|required";
		}
		
		// Setup form default values
		if( !is_null( $id ) AND !$this->input->post( 'submit' ) ){
			// Modify form, first load
			$menu = $this->menu_model->getMenu( 'menu.menu_position_id = ' . $position );
			$menu = $menu->row_array( );
			$this->validation->set_default_value( $menu );
		} elseif( is_null( $id ) AND !$this->input->post( 'submit' ) ){
			// Create form, first load
			$this->_set_menu_defaults();
		} elseif( $this->input->post('submit')){
			// Form submitted, check rules
			$this->validation->set_rules( $rules );
		}

		// RUN
		if( $this->validation->run( ) === FALSE) {
			$data['menu_position'] = $position;
			// Construct Menu dropdown
			$data['menu_dropdown'] = $this->menu_model->buildMenuDropdown( 'menu', 'id', $data['menu_position'] );
			//@todo: by other types need to change data, may be it can be more dynamical???
			switch ( $type ){
				case 'article':
					// Construct Article dropdown
					$this->load->model( 'article_model' );
					$data['article'] = $this->article_model->buildArticleDropdown( 'article', 'id' );
					break;
				case 'blog':
					// Construct Blog dropdown
					$this->load->module_model( 'blog', 'blog_model' );
					$data['blog'] = $this->blog_model->buildBlogDropdown( );
					break;
				case 'guestbook':
					// Construct Guestbook dropdown
					$this->load->module_model( 'guestbook', 'guestbook_model' );
					$data['guestbook'] = $this->guestbook_model->buildGuestbookDropdown( );
					break;
				case 'form':
					// Construct Form dropdown
					$this->load->module_model( 'form', 'form_model' );
					$data['form'] = $this->form_model->buildFormDropdown( );
					break;
				case 'checkin24':
					// Construct Checkin24 Object dropdown
					$this->load->module_model( 'checkin24', 'checkin24_model' );
					$data['checkin24'] = $this->checkin24_model->buildDropdown( );
					break;
				case 'events':
					// Construct Events Object dropdown
					//$this->load->module_model( 'events', 'events_model' );
					$data['start'] = '';
					$data['end'] = '';
					$data['highlights'] = '';
					break;	
			} //switch
			
			// Display form
			$this->validation->output_errors();
			$data['header'] = (is_null( $id ) ? $this->lang->line( 'create_menu' ) : $this->lang->line( 'edit_menu' ) );
			$this->bep_site->set_crumb( $data['header'],'article/user/menu/form' );
			$data['page'] = $this->config->item( 'backendpro_template_user' ) . "/form_menu_".$type;
			$data['menu'] = $this->website_model->getWebsiteUserMenu( );
			$data['module'] = 'article';
			$this->load->view( $this->_container, $data );
		} else {
			// Save form
			if( is_null( $id ) ) {
				// CREATE
				// Fetch form values
				$menu = $this->_get_menu_details( );
				
				$this->db->trans_start( );
				$this->menu_model->insert( $menu, $menu['menu_position_id'] );
				
				if( $this->db->trans_status( ) === TRUE ){
					$this->db->trans_commit();
					flashMsg( 'success', sprintf( $this->lang->line( 'menu_saved' ), $menu['type_id'] ) );
				} else {
					$this->db->trans_rollback( );
					flashMsg( 'error', sprintf( $this->lang->line('backendpro_action_failed'), $this->lang->line('userlib_create_user') ) );
				}
				redirect('article/user/menu/overview/' . $menu['menu_position_id'] );
			} else {
				// SAVE
				// Fetch form values
				$menu = $this->_get_menu_details( );
				
				$this->db->trans_start();
				$this->menu_model->update( $menu, $menu['id'] );

				if( $this->db->trans_status( ) === TRUE ) {
					$this->db->trans_commit( );
					flashMsg( 'success', sprintf( $this->lang->line( 'menu_saved' ), $menu['type'] ) );
				} else {
					$this->db->trans_rollback( );
					flashMsg( 'error', sprintf( $this->lang->line( 'backendpro_action_failed' ), $this->lang->line( 'userlib_edit_user' ) ) );
				}
				redirect('article/user/menu/overview/' . $menu['menu_position_id'] );
			}
		}
	} // form( );
	
	/**
	 * Display menu title translation form
	 *
	 * @access public
	 * @param integer $id Article ID
	 */
	function translate( $menu_id, $menu_position_id, $language_id = 1 ) {
		$data['menu_id'] 			= $menu_id;
		$data['menu_position_id'] 	= $menu_position_id;
		$data['language_id'] 		= $language_id;
		// get menu title from database if exists
		$translation = $this->menu_model->get_translation( $data );
		if( !empty( $translation ) ){
			$data['translation'] = $translation;
		}
		// RUN
		if( !$this->input->post( 'submit' ) ) {
			// Display form
			$data['header'] = $this->lang->line( 'translate_menu' );
			$this->bep_site->set_crumb( $data['header'],'article/user/menu/translate' );
			$data['page'] = $this->config->item( 'backendpro_template_user' ) . "/translate_menu";
			$data['menu'] = $this->website_model->getWebsiteUserMenu( );
			$data['module'] = 'article';
			$this->load->view( $this->_container, $data );
		} else {
			// Save form
			$menu['menu_id'] 			= $menu_id;
			$menu['menu_position_id'] 	= $menu_position_id;
			$menu['language_id'] 		= $language_id;
			$menu['title'] 				= $this->input->post( 'title' );
	
			$this->db->trans_start( );
			//if exists, we need to update
			if( !empty( $translation ) ){
				$title = $menu['title'];
				unset( $menu['title'] );
				$this->menu_model->update_translation( array( 'title' => $title ), $menu );
			} else {
				$this->menu_model->insert_translation( $menu );
			}
			
			if( $this->db->trans_status( ) === TRUE ){
				$this->db->trans_commit();
				flashMsg( 'success', sprintf( $this->lang->line( 'menu_saved' ), $menu['menu_id'] ) );
			} else {
				$this->db->trans_rollback( );
				flashMsg( 'error', sprintf( $this->lang->line('backendpro_action_failed'), $this->lang->line('userlib_create_user') ) );
			}
			redirect('article/user/menu/overview/' . $menu['menu_position_id'] );
		}
	} // translate( );
	
	/**
	 * Get Menu Position Details
	 *
	 * Load menu position detail values from the submitted form
	 *
	 * @access private
	 * @return array
	 */
	function _get_menu_position_details(){
		$data['id'] = $this->input->post( 'id' );
		$data['title'] = $this->input->post( 'title' );
		$data['position_id'] = $this->input->post( 'position_id' );
		$data['active'] = $this->input->post( 'active' );
		
		return $data;
	}	
	
	/**
	 * Display Menu Form
	 *
	 * @access public
	 * @param integer $id Menu position ID
	 */
	function form_position( $id = NULL ) {
		// VALIDATION FIELDS
		$fields['id'] = "ID";
		$fields['title'] = $this->lang->line( 'menu_position_title' );
		$fields['position_id'] = $this->lang->line( 'menu_position_id' );

		$this->validation->set_fields( $fields );

		// Setup validation rules
		if( is_null( $id ) ) {
			// Use create article rules (make sure no-one has the same short name)
			$rules['title'] = "trim|required";
			$rules['position_id'] = "required";
		} else {
			// Use edit article rules (make sure no-one other than the current user has the same short name)
			$rules['title'] = "trim|required";
			$rules['position_id'] = "required";
		}
		
		// Setup form default values
		if( !is_null( $id ) AND !$this->input->post( 'submit' ) ){
			// Modify form, first load
			$position_id = $this->menu_model->getMenuPosition( );
			$position_id = $position_id->row_array( );
			$this->validation->set_default_value( $position_id );
		} elseif( is_null( $id ) AND !$this->input->post( 'submit' ) ){
			//@todo: nothing to do here?
		} elseif( $this->input->post('submit')){
			// Form submitted, check rules
			$this->validation->set_rules( $rules );
		}

		// RUN
		if( $this->validation->run( ) === FALSE) {
			// Construct Position dropdown
			$data['position_id'] = $this->menu_model->buildPositionDropdown( );

			// Display form
			$this->validation->output_errors();

			$data['header'] = (is_null( $id ) ? $this->lang->line( 'create_menu_position' ) : $this->lang->line( 'edit_menu_position' ) );
			$this->bep_site->set_crumb( $data['header'],'article/user/menu/form_position/'.$id );
			$data['page'] = $this->config->item( 'backendpro_template_user' ) . "/form_menu_position";
			$data['menu'] = $this->website_model->getWebsiteUserMenu( );
			$data['module'] = 'article';
			$this->load->view( $this->_container, $data );
		} else {
			// Save form
			if( is_null( $id ) ) {
				// CREATE
				// Fetch form values
				$menu_position = $this->_get_menu_position_details( );

				$this->db->trans_start( );
				$this->menu_model->insertPosition( $menu_position );
				
				if( $this->db->trans_status( ) === TRUE ){
					$this->db->trans_commit();
					flashMsg( 'success', sprintf( $this->lang->line( 'menu_position_saved' ), $menu_position['title'] ) );
				} else {
					$this->db->trans_rollback( );
					flashMsg( 'error', sprintf( $this->lang->line('backendpro_action_failed'), $this->lang->line('userlib_create_user') ) );
				}
				redirect('article/user/menu');
			} else {
				// SAVE
				$menu_position = $this->_get_menu_position_details();
				
				$this->db->trans_start();
				$this->menu_model->updatePosition( $menu_position, $menu_position['id'] );

				if( $this->db->trans_status( ) === TRUE ) {
					$this->db->trans_commit( );
					flashMsg( 'success', sprintf( $this->lang->line( 'menu_position_saved' ), $menu_position['title'] ) );
				} else {
					$this->db->trans_rollback( );
					flashMsg( 'error', sprintf( $this->lang->line( 'backendpro_action_failed' ), $this->lang->line( 'userlib_edit_user' ) ) );
				}
				redirect('article/user/menu');
			}
		}
	} // form_position( );
	
	/**
	 * Delete Menu position
	 *
	 * @access public
	 */
	function delete_position( ) {
		if( FALSE === ( $selected = $this->input->post( 'select' ) ) ){
			redirect( 'article/user/menu', 'location' );
		}

		foreach( $selected as $menu_position ) {
			$this->db->delete( 'menu_position', array( 'id' => $menu_position ) );
		}

		flashMsg( 'success', $this->lang->line( 'menu_position_deleted' ) );
		redirect( 'article/user/menu', 'location' );
	}

    /**
	 * Update Menu entry position "down"
	 *
	 * @access public
	 */
	function down( $url, $position ) {
		
		$this->menu_model->down( $url, $position );
		
		flashMsg( 'success', $this->lang->line( 'menu_moved_down' ) );
		redirect( $_SERVER['HTTP_REFERER'], 'location' );
	}

    /**
	 * Update Menu entry position "up"
	 *
	 * @access up
	 */
	function up( $url, $position ) {
		
		$this->menu_model->up( $url, $position );
		
		flashMsg( 'success', $this->lang->line( 'menu_moved_down' ) );
		redirect( $_SERVER['HTTP_REFERER'], 'location' );
	}
	
    /**
	 * Delete Menu
	 *
	 * @access public
	 */
	function delete( $position ) {
		if( FALSE === ( $selected = $this->input->post( 'select' ) ) ){
			redirect( 'article/user/menu/overview/'.$position, 'location' );
		}

		foreach( $selected as $menu ) {
			// $menu is the url (unified)
			$this->menu_model->delete( $menu, $position );
		}

		flashMsg( 'success', $this->lang->line( 'menu_deleted' ) );
		redirect( 'article/user/menu/overview/'.$position, 'location' );
	}
	
	function lookup( ) {
		if( $this->menu_model->lookup( $this->input->post( 'queryString' ) ) ) {
			echo "Noch frei";
		} else {
			echo "Schon vergeben - Eingabe &auml;ndern";
		}
			
	}
}
/* End of file menu.php */
/* Location: ./modules/article/controllers/user/menu.php */
